<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8"/>
  <title>聊天室</title>
  <link rel="stylesheet" type="text/css" href="./css/index.css"/>
</head>
<body>
<div class="main">
  <div class="main-top">
    网页版客户端 socket.io demo
  </div>
  <div class="main-body">
    <section class="chatRoomInfo">
      <div class="info">当前共有<span class="chatNum">0</span>人在线。在线列表:&nbsp;<span class="chatList"></span></div>
    </section>
    <!--<section class="chatRoomTip">
      <div>子木加入到聊天室</div>
    </section>
    <section class="user clearfix">
      <span>子木</span>
      <div>
        测试测试测试测试测试测试测试测试测试试测试测试测试测试测试测试测试测试测试测试测试
      </div>
    </section>
    <section class="server clearfix">
      <span>子木</span>
      <div>
        测试测试测试
      </div>
    </section>-->
  </div>
  <div class="main-footer clearfix">
    <div class="input">
      <input type="text" name="msg" id="msg" value=""/>
    </div>
    <button type="button" class="send">发送</button>
  </div>
</div>
<script src="./js/jquery-2.1.0.js" type="text/javascript" charset="utf-8"></script>
<script src="https://cdn.bootcss.com/socket.io/2.0.4/socket.io.js"></script>
<script>
  var HOST = window.location.host; // '13.228.41.205:8000';
  /*按钮点击效果*/
  $('.send').mousedown(function () {
    $(this).css({ 'background': "#007aff", 'color': "#ffffff" });
  });
  $('.send').mouseup(function () {
    $(this).css({ 'background': "#e8e8e8", 'color': "#ffffff" });
  });

$(function () {
  const username = prompt('请输入您的姓名');
  console.log(username);
  if (!username) {
    alert('姓名必填');
    history.go(0);
  }
  //连接socket后端服务器
  const socket = io.connect("ws://" + HOST);
  //通知用户有用户登录
  socket.emit('userJoined', {username: username}, function (result) {
    console.log('用户加入,服务端返回:', result);
  });
  //监听新用户登录
  socket.on('login', function (o) {
    updateMsg(o, 'login');
  });
  //监听用户退出
  socket.on('logout', function (o) {
    updateMsg(o, 'logout');
  });

  //接送消息
  socket.on('message', function (obj) {
    obj.forEach(function (item) {
      if (item.user.name === username) {
        return;
      }
      let from = 'server';
      let MsgHtml = `<section class="${from} clearfix">
          <span>${item.user.name}</span>
          ${item.text? `<div>${item.text}</div>`: ''}
          ${item.image?`<div><image width="100px" height="100px" src="${item.image}"></div>`: ''}
          ${item.video?`<div><video width="100px" height="100px" src="${item.video}"></div>`: ''}
        </section>`;
      $('.main-body').append(MsgHtml);
      $('.main-body').scrollTop(99999);
    });
  });

  $(document).keypress(function(e) {
    // 回车键事件
    if(e.which == 13) {
      send();
    }
  });


  // 点击发送按钮
  $('.send'). on('click', send);
  function send() {
      const content = $('input[name="msg"]').val();
      if (content) {
        const obj = MSG(content);
        socket.emit('message', [obj], (result)=> {
          console.log(`发送消息:${result}`);
        });
        let MsgHtml = `<section class="user clearfix">
          <span>${username}</span>
          <div>${content}</div>
        </section>`;
        $('.main-body').append(MsgHtml);
        $('.main-body').scrollTop(99999);
        $('input[name="msg"]').val("");
      }
  }
  function MSG(text) {
    var time = new Date();
    return {
      _id: time.getTime()+'',
      text: text,
      createdAt: time,
      user: {
        _id: username,
        name: username,
      },
      extras: {}// 选填，可以在消息中添加附加字段
    };
  }
});

  function logout() {
    socket.disconnect();
    location.reload();
  }

  /*监听函数*/
  function updateMsg(o, action) {
    //当前在线列表
    var onlineUser = o.onlineUser;
    //当前在线数
    var onlineCount = o.onlineCount;
    //新加用户
    var user = o.user;
    //更新在线人数
    var userList = '';
    var separator = '';
    for (key in onlineUser) {
      userList += separator + onlineUser[key].username;
      separator = '、';
    }
    //跟新房间信息
    $('.chatNum').text(onlineCount);
    $('.chatList').text(userList);
    //系统消息
    if (action == 'login') {
      var sysHtml = '<section class="chatRoomTip"><div>' + user.username + '进入聊天室</div></section>';
    }
    if (action == "logout") {
      var sysHtml = '<section class="chatRoomTip"><div>' + user.username + '退出聊天室</div></section>';
    }
    $(".main-body").append(sysHtml);
    $('.main-body').scrollTop(99999);
  }
</script>
</body>
</html>
